package com.mike;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class FileMaker {
	
	private static final String TITLE = "%%title%%";
	private static final String SRC = "%%source%%";
	
	private static final String s_dropBoxUrl = "https://dl.dropboxusercontent.com/u/31761783/csci106/coursecontent/";
	private static String s_templateText = "";
	
	
	static {
		BufferedReader reader = new BufferedReader(new InputStreamReader(FileMaker.class.getResourceAsStream("template.html")));
		String line = null;
		try {
			while((line = reader.readLine()) != null){
				s_templateText += line;
				s_templateText += "\r\n";
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(2);
		} finally {
			try {reader.close(); } catch (Exception e2){}
		}
	}
	
	private static String read(final File file){
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			StringBuilder builder = new StringBuilder();
			String line = null;
			while((line = reader.readLine()) != null){
				builder.append(line);
			}
			return builder.toString();
		} catch (IOException e) {
			return "";
		} finally {
			if(reader != null)
				try {reader.close(); } catch (Exception e2){}
		}
	}
	
	private static void write(final File file, String data){
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(file));
			writer.write(data);
		} catch (Exception e){
			return;
		} finally {
			if(writer != null)
				try { writer.close(); } catch (Exception e2) {}
		}
	}
	
	private static void findFiles(File path, final String basePath, final String outPath) throws UnsupportedEncodingException{
		if(path.isDirectory()){
			File[] files = path.listFiles();
			for(File file : files){
				findFiles(file, basePath, outPath);
			}
		} else {
			String name = path.getName();
			if(!name.endsWith(".html"))
				return;
			String[] parts = name.split("\\.");
			if(parts.length != 2)
				return;
			try { Integer.parseInt(parts[0]); } catch (Exception e){ return; }
			
			Document doc = Jsoup.parse(read(path));
			String output = s_templateText;			
			output = output.replace(TITLE, doc.title());
			String relPath = path.getAbsolutePath().substring(basePath.length()+1);
			relPath = relPath.replaceAll("\\\\", "/");
			String url = s_dropBoxUrl+relPath;
			output = output.replace(SRC, url);
			String outFilePath = outPath + File.separatorChar + relPath.replace(path.getName(),  "").replace("/", "");
			File outputFileDir = new File(outFilePath);
			if(!outputFileDir.exists() && !outputFileDir.mkdirs())
				return;
			String fileName = (doc.title() + ".html").replaceAll("[^a-zA-Z0-9- \\\\.]", "");
			File outFile = new File(outFilePath + File.separator + fileName);
			write(outFile, output);
			
		}
			
	}

	public static void main(String[] args) {
		if(args.length != 2){
			System.err.println("Please provide a folder path with html files. And a output folder path");
			return;
		}
		String strPath = args[0];
		File filePath = new File(strPath);
		if(!filePath.isDirectory()){
			System.err.println(strPath + " is not a directory");
			return;
		}
		
		String strOutDirPath = args[1];
		File outPath = new File(strOutDirPath);
		if(!outPath.isDirectory()){
			System.err.println(strOutDirPath + " is not a directory");
			return;
		}
		
		try {
			findFiles(filePath, filePath.getAbsolutePath(), outPath.getAbsolutePath());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

	}

}
